import Vue from 'vue';
import UploadSidebar from '../components/UploadSidebar';

// 创建全局组件管理类
class GlobalComponentManager {
  constructor() {
    this.components = {};
  }

  // 注册全局组件
  registerComponent(name, component) {
    // 1. 全局注册组件，使其可以在任意页面中通过标签使用
    Vue.component(name, component);
  }

  // 创建并挂载组件实例到指定容器
  mountComponentToContainer(name, component, container = document.body) {
    if (!this.components[name]) {
      const instance = new Vue({
        render: h => h(component)
      }).$mount();
      
      container.appendChild(instance.$el);
      this.components[name] = {
        instance,
        vm: instance.$children[0] || instance
      };
    }
    
    return this.components[name].vm;
  }

  // 获取已挂载的组件实例
  getComponentInstance(name) {
    return this.components[name]?.vm;
  }

  // 销毁组件实例
  destroyComponent(name) {
    if (this.components[name]) {
      const { instance } = this.components[name];
      instance.$destroy();
      if (instance.$el && instance.$el.parentNode) {
        instance.$el.parentNode.removeChild(instance.$el);
      }
      delete this.components[name];
    }
  }
}

// 创建单例实例
const globalComponentManager = new GlobalComponentManager();

// 导出管理器实例和插件安装方法
export { globalComponentManager };

export default {
  install(Vue) {
    // 注册全局方法
    Vue.prototype.$globalComponents = globalComponentManager;
  }
};